package com.iuchannel.android.provider.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;

/**
 * This class returns the result String of HttpGet or HttpPost
 * 
 * @author Yohan Chang
 *
 */
public class GetHttp{

	public static final String METHOD_GET="GET";
	public static final String METHOD_POST="POST";
	
	/**
	 * 
	 * @param url
	 * @return String
	 */
	public static String getUrl(String url){
		return getUrl(url, "");
	}
	
	/**
	 * 
	 * @param url
	 * @param cookie
	 * @return String
	 */
	public static String getUrl(String url, String cookie){
		String result="";
		try {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpGet get = null;
			get = new HttpGet(url);
			
			if(cookie!=null && cookie.length()>0){
				try{
					URI uri = new URI(url);
					String urlDomain=uri.getHost();
					urlDomain=urlDomain.startsWith("www.")?urlDomain.substring(4):urlDomain;
					
			    	CookieStore cookieStore = new BasicCookieStore();
			        String[] cookie_parts = cookie.split(";");
			        for(int t=0;t < cookie_parts.length;t++){
			            String[] cookieContent = cookie_parts[t].split("=");
			            Cookie tempCookie = new BasicClientCookie(cookieContent[0],cookieContent[1]);
			            ((BasicClientCookie) tempCookie).setDomain(urlDomain);
			            cookieStore.addCookie(tempCookie);
			        }
			        httpclient.setCookieStore(cookieStore);						
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			
			HttpResponse response = httpclient.execute(get);
			
			
			// get Result
			HttpEntity resEntity = response.getEntity();

			InputStream is = resEntity.getContent();
			InputStreamReader reader = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(reader);
			String temp = "";
			if ((temp = br.readLine()) != null) {
				result += temp;
			}

			br.close();
			is.close();
			
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return result;
	}
		
}